/*
 * Created on2022/6/11 15:54
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.yzbdl.lanius.core.metastore;

import cn.hutool.core.io.FileUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.ApplicationPathUtil;
import org.yzbdl.lanius.core.constant.LocalDir;
import org.yzbdl.lanius.util.LogUtil;
import org.yzbdl.lanius.util.VersionUtil;

import java.sql.SQLException;
import java.util.Date;
import java.util.EnumSet;

/**
 * TODO
 *
 * @author hs@yzbdl.ac.cn
 * @version 1.0
 * @date 2019/6/11 15:54
 */
public class EngineDb {

    // 数据库主版本更新标识
    private static final int majorVersion = 5;
    // 数据库副版本更新标识
    private static final int minorVersion = 0;

    public static void init() throws Exception {
        String dbPath = LocalDir.BASE + LocalDir.separator + "data" + LocalDir.separator;
//        String ver = VersionUtil.getLaniusVersionTopTwo();
//        // 拼接版本目录
//        if (StringUtils.isNotBlank(ver)) {
//            dbPath += ver + LocalDir.separator;
//        }
        if (!FileUtil.exist(dbPath + "lanius.mv.db")) {
            try {
                EngineDb.initDb(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            LdrVersionEntity version = null;
            try {
                version = HutoolDb.useDynamicUrlDb().query("select * from ldr_version",
                        new BeanHandler<LdrVersionEntity>(LdrVersionEntity.class));
            } catch (Exception e) {
            }
            if (version == null) {
                EngineDb.initDb(true);
            } else if (version.getMajorVersion() < EngineDb.majorVersion) {
                version.setVersion(VersionUtil.getLaniusVersion());
                version.setMajorVersion(EngineDb.majorVersion);
                version.setMinorVersion(EngineDb.minorVersion);
                version.setUpdateTime(new Date());
                HutoolDb.useDynamicUrlDb().update(Entity.create("ldr_version").parseBean(version, true, false),
                        Entity.create("ldr_version").set("id", version.getId()));
                EngineDb.initDb(false);
            }
        }
    }

    private static void initDb(boolean initVersion) throws SQLException {
        long start = System.currentTimeMillis();
        Configuration config = new Configuration().configure();
        EngineDb.repUrlVersion(config);
        ServiceRegistry serviceRegistry =
                new StandardServiceRegistryBuilder().configure().applySettings(config.getProperties()).build();
        Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
        SchemaUpdate update = new SchemaUpdate();
        update.execute(EnumSet.of(TargetType.DATABASE), metadata);

        long end = System.currentTimeMillis();
        LogUtil.debug("数据库表结构更新耗时：" + (end - start));

        if (initVersion) {
            Entity entity =
                    Entity.create("ldr_version").set("major_version", EngineDb.majorVersion).set("minor_version", EngineDb.minorVersion)
                            .set("create_time", new Date()).set("version_", VersionUtil.getLaniusVersion());
            HutoolDb.useDynamicUrlDb().insert(entity);
        }
    }

    /**
     * 替换url参数信息，新增加数据库路径
     *
     * @param config
     */
    private static void repUrlVersion(Configuration config) {
        // String dbHome = Const.getUserHomeDirectory();
        String dbHome = ApplicationPathUtil.getPath();
        // String ver = VersionUtil.getLaniusVersionTopTwo();
        String dbUrl = config.getProperty("hibernate.connection.url").replace("${" + Const.H2_URL_DB_DIR + "}", dbHome);
        // .replace("${" + Const.H2_URL_PARAMS + "}", ver)
        config.setProperty("hibernate.connection.url", dbUrl);
        config.setProperty("connection.url", dbUrl);
    }

}
